package com.example.car.vm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.example.car.entity.Car
import com.example.car.entity.GetPayCar
import com.example.car.entity.Pay
import com.example.car.entity.PayCar
import com.example.car.entity.PostCar
import com.example.car.model.CarRepository
import com.example.common.view.vm.BaseViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import javax.inject.Inject
@HiltViewModel
class CarViewModel @Inject constructor(private val repo:CarRepository):BaseViewModel() {
    val mCarSuccess = MutableLiveData<List<Car>>()
    fun getCar(){
        mViewModelScope.launch(mDispatcher){
            val (code,data,message) = repo.getCar()
            if(code == 200){
                mCarSuccess.postValue(data)
            }else{
                mError.postValue(message)
            }
        }
    }
    val mPostCarSuccess = MutableLiveData<PostCar>()
    fun postCar(postCar:PostCar){
        mViewModelScope.launch(mDispatcher){
            val json = GsonUtils.toJson(postCar)
            val (code,data,message) = repo.postCar(RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json))
            if(code == 200){
                mPostCarSuccess.postValue(data)
            }else{
                mError.postValue(message)
            }
        }
    }
    val mPayCarSuccess = MutableLiveData<Pay>()
    fun payCar(payCar: PayCar){
        mViewModelScope.launch(mDispatcher){
            val (code,data,message) = repo.payCar(payCar)
            if(code == 200){
                mPayCarSuccess.postValue(data)
            }else{
                mError.postValue(message)
            }
        }
    }
    val mGetPayCarSuccess = MutableLiveData<GetPayCar>()
    fun getPayCar(id:Int){
        mViewModelScope.launch(mDispatcher){
            val (code,data,message) = repo.getPayCar(id)
            if(code == 200){
                mGetPayCarSuccess.postValue(data)
            }else{
                mError.postValue(message)
            }
        }
    }
}